using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Event;
using Tools.Common.ServiceLocator;
using Webshop20.Domain.Catalog.Core;
using Webshop20.Domain.Customers.Services.Contracts;

namespace Webshop20.Infrastructure.Persistence.NH.Interceptors
{
    public class VisitorPostLoadEventListener: NHibernate.Event.Default.DefaultInitializeCollectionEventListener 
    {

        public override void OnInitializeCollection(InitializeCollectionEvent @event)
        {
           base.OnInitializeCollection(@event);
            var visitors = @event.Collection.GetValue() as IEnumerable<Visitor>;
            if(visitors != null)
            {
                var customerInformationService
                    = ServiceLocator.Current.Resolve<ICustomerInformationService>();

                var customers = customerInformationService
                    .GetCustomersById(visitors.Select(visitor => visitor.Id));

                foreach (var visitor in visitors)
                {
                    var customer = customers.Where(cust => cust.Id == visitor.Id).FirstOrDefault();
                    visitor.FirstName = customer.FirstName;
                    visitor.LastName = customer.LastName;
                    visitor.EMail = customer.EMail;
                }

            }

        }

        

         
    }
}